package com.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

public class HtmlUtil
{
  public static void writerJson(HttpServletResponse response, String jsonStr)
  {
    writer(response, jsonStr);
  }

  public static void writerJson(HttpServletResponse response, Object object) {
    writer(response, JSON.toJSONString(object, new SerializerFeature[] { SerializerFeature.DisableCircularReferenceDetect }));
  }

  private static void writer(HttpServletResponse response, String str)
  {
    try {
      response.setHeader("Pragma", "No-cache");
      response.setHeader("Cache-Control", "no-cache");
      response.setCharacterEncoding("UTF-8");
      PrintWriter out = null;
      out = response.getWriter();
      out.print(str);

      out.flush();
      out.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  public static Map<String, String> getParameterMap(HttpServletRequest request)
  {
    Map properties = request.getParameterMap();

    Map returnMap = new HashMap();
    Iterator entries = properties.entrySet().iterator();

    String name = "";
    String value = "";
    while (entries.hasNext()) {
      Map.Entry entry = (Map.Entry)entries.next();
      name = (String)entry.getKey();
      Object valueObj = entry.getValue();
      if (valueObj == null) {
        value = "";
      } else if ((valueObj instanceof String[])) {
        String[] values = (String[])valueObj;
        for (int i = 0; i < values.length; i++) {
          value = values[i] + ",";
        }
        value = value.substring(0, value.length() - 1);
      } else {
        value = valueObj.toString();
      }
      returnMap.put(name, value);
    }
    return returnMap;
  }

  public static String Encode(String str, String ucoder)
  {
    String s = "";
    try {
      s = URLEncoder.encode(str, ucoder);
    }
    catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }
    return s;
  }

  public static void ShowImg(String path, HttpServletResponse response)
    throws IOException
  {
    File picFile = new File(path);
    if (!picFile.exists()) {
      return;
    }
    response.setContentType("image/jpeg; charset=utf-8");

    ServletOutputStream outputStream = response.getOutputStream();
    FileInputStream inputStream = new FileInputStream(picFile);
    byte[] buffer = new byte[1024];
    int i = -1;
    while ((i = inputStream.read(buffer)) != -1) {
      outputStream.write(buffer, 0, i);
    }
    outputStream.flush();
    outputStream.close();
    inputStream.close();
    outputStream = null;
  }

  public static void ShowPdf(String path, HttpServletResponse response)
    throws IOException
  {
    File picFile = new File(path);
    if (!picFile.exists()) {
      return;
    }
    response.setContentType("application/pdf; charset=utf-8");

    ServletOutputStream outputStream = response.getOutputStream();
    FileInputStream inputStream = new FileInputStream(picFile);
    byte[] buffer = new byte[1024];
    int i = -1;
    while ((i = inputStream.read(buffer)) != -1) {
      outputStream.write(buffer, 0, i);
    }
    outputStream.flush();
    outputStream.close();
    inputStream.close();
    outputStream = null;
  }

  public static Object getSessionValue(HttpServletRequest request, String key)
  {
    HttpSession session = request.getSession();
    return session.getAttribute(key);
  }

  public static Map getUserInfoFromSession(HttpServletRequest request)
  {
    return (Map)getSessionValue(request, "CURRENT_LOGIN_USER");
  }

  public static void clearSession(HttpServletRequest request)
  {
    HttpSession session = request.getSession();
    session.removeAttribute("CURRENT_LOGIN_USER");
    session.removeAttribute("CURRENT_USER_ROLE");

    session.setAttribute("CURRENT_LOGIN_USER", null);
    session.setAttribute("CURRENT_USER_ROLE", null);

    session.invalidate();
  }

  public static void saveCookie(HttpServletResponse response, Map dataMap)
  {
    String username = dataMap.get("username").toString();
    String password = dataMap.get("password").toString();

    String cookieValue = username;

    Cookie cookie = new Cookie("com.kq.erp", cookieValue);

    cookie.setMaxAge(2592000);

    cookie.setPath("/");

    response.addCookie(cookie);
  }

  public static String readCookie(HttpServletRequest request)
  {
    String cookieValue = "";
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
      int len = cookies.length;
      for (int i = 0; i < len; i++) {
        Cookie cookie = cookies[i];
        if ("com.kq.erp".equals(cookie.getName())) {
          cookieValue = cookie.getValue();
          break;
        }
      }
    }
    return cookieValue;
  }

  public static void clearCookie(HttpServletRequest request, HttpServletResponse response)
  {
    Cookie[] cookies = request.getCookies();
    if (cookies != null)
      for (int i = 0; i < cookies.length; i++) {
        Cookie cookie = cookies[i];
        if ("com.kq.erp".equals(cookie.getName())) {
          cookie.setPath("/");

          cookie.setMaxAge(0);
          response.addCookie(cookie);
        }
      }
  }
}